print("202509021528")
-- KRNL HttpGet 专用解决方案
-- 环境: toblox krnl 编辑器，luau5.1 版本
-- 限制: 只能使用 game:HttpGet()，不能使用 HttpService:RequestAsync

local HttpService = game:GetService("HttpService")

-- 安全的文件写入函数
local function safeWriteFile(filename, content)
    local success, err = pcall(function()
        appendfile(filename, content)
    end)
    
    if not success then
        local writeSuccess, writeErr = pcall(function()
            writefile(filename, content)
        end)
        
        if not writeSuccess then
            print("文件写入失败: " .. filename .. " - " .. tostring(writeErr))
        end
    end
end

-- 方案1: 使用 Loki 标准格式发送日志数据（推荐）
local function uploadToLokiStandard(logMessage, metadata)
    local success, err = pcall(function()
        -- 获取当前时间戳（纳秒级）
        local timestamp = os.time() * 1000000000
        
        -- 构建 Loki 标准数据
        local lokiData = {
            streams = {
                {
                    stream = {
                        app = "u7playearn",
                        log_type = metadata and metadata.log_type or "general",
                        username = metadata and metadata.username or "test_user"
                    },
                    values = {
                        { tostring(timestamp), logMessage }
                    }
                }
            }
        }
        
        -- 如果有订单相关信息，添加到 stream 标签中
        if metadata and metadata.order_id then
            lokiData.streams[1].stream.order_id = tostring(metadata.order_id)
        end
        if metadata and metadata.order_status then
            lokiData.streams[1].stream.order_status = tostring(metadata.order_status)
        end
        
        -- 转换为 JSON 并 URL 编码
        local jsonData = HttpService:JSONEncode(lokiData)
        local encodedData = HttpService:UrlEncode(jsonData)
        
        -- 构建转发请求参数
        local forwardParams = {
            url = "https://lokipush.shopwegame.com/loki/api/v1/push",
            method = "POST",
            data = encodedData
        }
        
        -- 构建查询字符串
        local queryParts = {}
        for key, value in pairs(forwardParams) do
            table.insert(queryParts, key .. "=" .. tostring(value))
        end
        local queryString = table.concat(queryParts, "&")
        
        -- 构建 URL
        local url = "https://forward.shopwegame.com/forward?" .. queryString
        
        print("Loki 标准格式 GET 请求:")
        print("URL: " .. url)
        
        -- 发送 GET 请求
        local response = game:HttpGet(url, true)
        
        print("Loki 标准格式 GET 响应: " .. response)
        
        -- 记录上传结果
        safeWriteFile("loki_standard_log.txt", string.format("[%s] Loki 标准格式上传结果: %s\n", os.date("%Y-%m-%d %H:%M:%S"), response))
        
        return response
    end)
    
    if not success then
        print("Loki 标准格式上传失败: " .. tostring(err))
        safeWriteFile("loki_standard_error.txt", string.format("[%s] Loki 标准格式上传失败: %s\n", os.date("%Y-%m-%d %H:%M:%S"), tostring(err)))
    end
end

-- 方案2: 使用 URL 编码的 JSON 数据
local function uploadToLokiEncoded(logMessage, metadata)
    local success, err = pcall(function()
        -- 获取当前时间戳（纳秒级）
        local timestamp = os.time() * 1000000000
        
        -- 构建 stream 标签
        local stream = {
            app = "u7playearn",
            log_type = metadata and metadata.log_type or "general",
            username = metadata and metadata.username or "test_user"
        }
        
        -- 如果有订单相关信息，添加到标签中
        if metadata and metadata.order_id then
            stream.order_id = tostring(metadata.order_id)
        end
        if metadata and metadata.order_status then
            stream.order_status = tostring(metadata.order_status)
        end
        
        -- 构建 Loki 请求数据
        local lokiData = {
            streams = {
                {
                    stream = stream,
                    values = {
                        { tostring(timestamp), logMessage }
                    }
                }
            }
        }
        
        -- 转换为 JSON 字符串
        local jsonData = HttpService:JSONEncode(lokiData)
        
        -- 构建转发请求数据
        local forwardData = {
            url = "https://lokipush.shopwegame.com/loki/api/v1/push",
            method = "POST",
            data = jsonData
        }
        
        -- 转换为 JSON 并 URL 编码
        local forwardJson = HttpService:JSONEncode(forwardData)
        local encodedData = HttpService:UrlEncode(forwardJson)
        
        -- 构建 URL
        local url = "https://forward.shopwegame.com/forward?data=" .. encodedData
        
        print("编码 GET 请求:")
        print("URL: " .. url)
        
        -- 发送 GET 请求
        local response = game:HttpGet(url, true)
        
        print("编码 GET 响应: " .. response)
        
        -- 记录上传结果
        safeWriteFile("loki_encoded_log.txt", string.format("[%s] 编码上传结果: %s\n", os.date("%Y-%m-%d %H:%M:%S"), response))
        
        return response
    end)
    
    if not success then
        print("编码 Loki 上传失败: " .. tostring(err))
        safeWriteFile("loki_encoded_error.txt", string.format("[%s] 编码Loki上传失败: %s\n", os.date("%Y-%m-%d %H:%M:%S"), tostring(err)))
    end
end

-- 方案3: 增强本地日志（备选方案）
local function enhancedLocalLogging(logMessage, metadata)
    local success, err = pcall(function()
        -- 构建完整的日志条目
        local logEntry = {
            timestamp = os.date("%Y-%m-%d %H:%M:%S"),
            unix_timestamp = os.time(),
            message = logMessage,
            metadata = metadata or {},
            app = "u7playearn",
            username = metadata and metadata.username or "test_user",
            log_type = metadata and metadata.log_type or "general"
        }
        
        -- 如果有订单相关信息，添加到日志中
        if metadata and metadata.order_id then
            logEntry.order_id = tostring(metadata.order_id)
        end
        if metadata and metadata.order_status then
            logEntry.order_status = tostring(metadata.order_status)
        end
        
        -- 转换为 JSON
        local jsonLog = HttpService:JSONEncode(logEntry)
        
        -- 写入增强日志文件
        safeWriteFile("enhanced_log.txt", jsonLog .. "\n")
        
        -- 同时写入简单日志作为备份
        local simpleLog = string.format("[%s] %s", os.date("%Y-%m-%d %H:%M:%S"), logMessage)
        safeWriteFile("simple_log.txt", simpleLog .. "\n")
        
        -- 写入 Loki 格式的日志（便于后续导入）
        local lokiTimestamp = os.time() * 1000000000
        local lokiLog = string.format('{"streams":[{"stream":{"app":"u7playearn","log_type":"%s","username":"%s"},"values":[["%s","%s"]]}]}',
            logEntry.log_type,
            logEntry.username,
            tostring(lokiTimestamp),
            logMessage:gsub('"', '\\"')
        )
        safeWriteFile("loki_format_log.txt", lokiLog .. "\n")
        
        print("增强本地日志已写入: " .. jsonLog)
        
        return "本地日志已保存"
    end)
    
    if not success then
        print("增强本地日志失败: " .. tostring(err))
        -- 最后的回退方案
        local fallbackLog = string.format("[%s] %s", os.date("%Y-%m-%d %H:%M:%S"), logMessage)
        safeWriteFile("fallback_log.txt", fallbackLog .. "\n")
    end
end

-- 方案4: 测试网络连接
local function testNetworkConnection()
    print("=== 测试网络连接 ===")
    
    -- 测试基本网络连接
    local success, result = pcall(function()
        return game:HttpGet("https://httpbin.org/get", true)
    end)
    
    if success then
        print("基本网络连接: 成功")
        print("响应长度: " .. #result .. " 字符")
    else
        print("基本网络连接: 失败 - " .. tostring(result))
    end
    
    -- 测试 Loki 端点可访问性
    local lokiSuccess, lokiResult = pcall(function()
        return game:HttpGet("https://lokipush.shopwegame.com/", true)
    end)
    
    if lokiSuccess then
        print("Loki 端点: 可访问")
    else
        print("Loki 端点: 不可访问 - " .. tostring(lokiResult))
    end
    
    -- 测试转发服务可访问性
    local forwardSuccess, forwardResult = pcall(function()
        return game:HttpGet("https://forward.shopwegame.com/", true)
    end)
    
    if forwardSuccess then
        print("转发服务: 可访问")
    else
        print("转发服务: 不可访问 - " .. tostring(forwardResult))
    end
end

-- 主测试函数
local function testAllMethods()
    print("=== 测试所有 HttpGet 方法 ===")
    
    -- 首先测试网络连接
    testNetworkConnection()
    
    local testMessage = "测试日志消息 - " .. os.date("%Y-%m-%d %H:%M:%S")
    local testMessageData = {
        robloxUsername = "pssmurf0078",
        orderId = "2025",
        orderStatus = 2,
        rawData = {
            order_id = "2025",
            trade_num = 1,
            user = "pssmurf0077",
            orderProductId = "20251",
            orderStatus = 2,
            itemId = "Saw"
        },
        url= "https://u7playearn.shopwegame.com/dev-api/play-earn/api/order/sync?authSecret=8f9dbe334ca364eac2b18ca437fde25d&orderId=2025&orderStatus=2",
        timestamp= 1756457608,
        orderProductId="202509021431"
    }
    local testMessageJsonLog = HttpService:JSONEncode(testMessageData)
    print("数据测试 - " .. tostring(testMessageJsonLog))
    -- local testMessageUrlEncode = HttpService:UrlEncode(testMessageJsonLog)
    -- print("数据测试UrlEncode - " .. tostring(testMessageUrlEncode))
    local testMessage =    tostring(testMessageJsonLog)
    print("数据测试testMessage - " .. testMessage)
    local testMetadata = {
        log_type = "test",
        order_id = "202509021523",
        order_status = "2",
        username = "pssmurf0078"
    }
    
    print("\n1. 测试 Loki 标准格式:")
    uploadToLokiStandard(testMessage, testMetadata)
    
    -- print("\n2. 测试编码 GET 请求:")
    -- uploadToLokiEncoded(testMessage, testMetadata)
    
    -- print("\n3. 测试增强本地日志:")
    -- enhancedLocalLogging(testMessage, testMetadata)
    
    print("\n=== 测试完成 ===")
end

-- 运行测试
testAllMethods()

-- 如果只想测试特定方法，可以单独调用:
-- uploadToLokiStandard("单条测试日志", { log_type = "test" })
-- uploadToLokiEncoded("单条测试日志", { log_type = "test" })
-- enhancedLocalLogging("单条测试日志", { log_type = "test" })
-- testNetworkConnection()
